#!/bin/bash

echo "===================================="
echo "  图片小程序后端服务启动脚本"
echo "===================================="
echo

# 检查 Node.js
if ! command -v node &> /dev/null; then
    echo "[错误] 未找到 Node.js，请先安装 Node.js"
    exit 1
fi

# 检查 pnpm
if ! command -v pnpm &> /dev/null; then
    echo "[错误] 未找到 pnpm，请先安装: npm install -g pnpm"
    exit 1
fi

# 检查依赖是否安装
if [ ! -d "api/node_modules" ]; then
    echo "[提示] 检测到未安装依赖，正在安装..."
    pnpm run install:all
    if [ $? -ne 0 ]; then
        echo "[错误] 依赖安装失败"
        exit 1
    fi
    echo "[提示] 依赖安装完成..."
fi

# 检查 Prisma Client 是否生成（检查 @prisma/client 是否存在）
if [ ! -d "api/node_modules/@prisma/client" ]; then
    echo "[提示] 生成 Prisma Client..."
    cd shared/prisma || exit 1
    if [ ! -d "node_modules" ]; then
        echo "[信息] 在 shared/prisma 目录安装依赖..."
        pnpm install
        if [ $? -ne 0 ]; then
            echo "[错误] 依赖安装失败"
            cd ../..
            exit 1
        fi
    fi
    echo "[信息] 生成 Prisma Client..."
    npx prisma generate --schema=schema.prisma
    if [ $? -ne 0 ]; then
        echo "[错误] Prisma Client 生成失败"
        cd ../..
        exit 1
    fi
    cd ../.. || exit 1
fi

# 检查数据库是否初始化
if [ ! -f "shared/prisma/data.db" ]; then
    echo "[提示] 检测到数据库未初始化，正在初始化..."
    cd shared/prisma || exit 1
    echo "[信息] 运行数据库迁移..."
    npx prisma migrate dev --name init --schema=schema.prisma
    if [ $? -ne 0 ]; then
        echo "[错误] 数据库初始化失败"
        cd ../..
        exit 1
    fi
    cd ../.. || exit 1
fi

echo "[信息] 启动服务..."
echo

# 启动三个服务
cd api && pnpm run dev &
API_PID=$!

cd ../admin && pnpm run dev &
ADMIN_PID=$!

cd ../admin-frontend && pnpm run dev &
FRONTEND_PID=$!

cd ..

echo
echo "===================================="
echo "  服务启动完成！"
echo "===================================="
echo "API 服务:    http://localhost:3000"
echo "Admin 服务:  http://localhost:3001"
echo "管理后台:    http://localhost:3002"
echo
echo "按 Ctrl+C 停止所有服务"

# 等待中断信号
trap "kill $API_PID $ADMIN_PID $FRONTEND_PID; exit" INT TERM

wait

